package lingou.homework.postbar.controller.tool;

import jakarta.servlet.http.HttpSession;
import lingou.homework.postbar.controller.proto.resp.Response;
import lingou.homework.postbar.domain.Post;
import lingou.homework.postbar.exception.BusinessException;

public class SessionHelper {
    private static final String USER_LOGIN = "userID";
    public static final Response NOT_LOGGED = Response.ofFailure("当前未登陆账号，请先登录！");
    public static boolean isLogin(HttpSession session) {
        return session.getAttribute(USER_LOGIN) != null;
    }
    public static long checkLogin(HttpSession session) {
        Long id = getCurrentUser(session);
        if(id == null) throw BusinessException.NO_LOGIN;
        return id;
    }
    public static void login(HttpSession session, long id){
        session.setAttribute(USER_LOGIN, id);
    }
    public static Long getCurrentUser(HttpSession session){
        return (Long) session.getAttribute(USER_LOGIN);
    }
    public static void logout(HttpSession session){
        session.setAttribute(USER_LOGIN, null);
        session.invalidate();
    }
    public static Response selfOperation(HttpSession session, Post post) {
        Long userId = SessionHelper.getCurrentUser(session);
        if(userId == null) return SessionHelper.NOT_LOGGED;
        if(!post.getUserId().equals(userId)) return Response.NO_PERMISSION;
        return null;
    }
}
